<template>
  <div class="index-box" ref="index">
    <el-row :gutter="10">
      <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
        <div class="search" ref="search">
          <el-form :inline="true" :model="searchForm" size="small" ref="searchForm" @submit.native.prevent
            class="demo-form-inline" id="searchBox">

            <el-form-item prop="storeName">
                <el-input v-model="searchForm.storeName" clearable placeholder="商家名称"></el-input>
            </el-form-item>

            <el-form-item class="clearfix">
              <el-button type="primary" @click="handleSearch()" icon="el-icon-search">搜索</el-button>
              <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <div class="table" ref="table">
          <el-table :data="dataList" style="width: 100%;" row-key="id" border :height="tableHeight"
            @selection-change="handleSelectionChange"  stripe v-loading="loading" @sort-change="handleTablechangeSort">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column prop="storeCode" label="商户编号" ></el-table-column>
            <el-table-column prop="name" label="门店logo"  width="100">
              <template #default="scope">
                 <el-image :src="scope.row.storeLogo" fit="fill"  class="img" v-image-preview></el-image>
              </template>
            </el-table-column>
            <el-table-column prop="storeName" label="商家门店名称" width="150" show-overflow-tooltip align="center"></el-table-column>

            <el-table-column prop="categoryName" label="商家类型"  align="center"></el-table-column>
            <el-table-column prop="accountType" label="账号类型"  align="center">
              <template slot-scope="scope">
                <div class="ellipsis-item3">{{scope.row.accountType=='1'?'对私账号':"对公账号"}}</div>
              </template>
            </el-table-column>
            <el-table-column prop="areaName" label="门店所在区域"  align="center" width="200">
              <template slot-scope="scope">
                <div class="ellipsis-item3">{{scope.row.areaName}}</div>
              </template>
            </el-table-column>
            <el-table-column prop="address" label="详细地址" width="200"></el-table-column>

          <!--  <el-table-column prop="markupRate" label="商品加价比例"  align="center">
              <template slot-scope="scope">
                <span>{{scope.row.markupRate}}%</span>
              </template>
            </el-table-column> -->
            <el-table-column prop="insertDate" label="加入日期"  align="center" sortable>
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="状态"  align="center">
              <template #default="scope">
                <div class="d-flex justify-center"><MySwitch :value.sync="scope.row.storeStatus" text="启用|禁用" textValue="1|2" @changeStatus="handleChangeStatus(scope.row)" ></MySwitch></div>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="操作"  width="130" fixed="right" align="center">
              <template #default="scope">
                  <div class="verticalBtn">

                  <el-button
                    size="medium"
                    type="text"
                    icon="el-icon-document"
                    @click="handleLook(scope.$index, scope.row)"
                  >查看</el-button>
                  <el-button
                     size="medium"
                     type="text"
                     icon="el-icon-edit"
                     @click="handleSet(scope.$index, scope.row)"
                   >设置</el-button>
                 <!-- <el-dropdown size="medium" >
                    <span class="el-dropdown-link">
                      <i class="el-icon-d-arrow-right el-icon--right"></i>更多
                    </span>
                    <el-dropdown-menu slot="dropdown" >
                       <el-dropdown-item @click.native="handleEditStoreNumber(scope.$index, scope.row)" v-has="'user:storeManage:editStoreNumber'">修改商户号</el-dropdown-item>
                       <el-dropdown-item @click.native="handleRqCode(scope.$index, scope.row)" v-has="'user:storeManage:QR'">二维码</el-dropdown-item>
                       <el-dropdown-item @click.native="handleDelt(scope.$index, scope.row)" v-has="'user:storeManage:del'">删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown> -->
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="page" ref="page">
         <MyPagination
            v-show="total"
           :total="total"
           :page.sync="searchForm.pageNum"
           :limit.sync="searchForm.pageSize"
           @pagination="dataInfo"
         />
        </div>
      </el-col>
    </el-row>

    <!-- 设置 -->
    <el-dialog title="设置商家服务费" width="600px" v-dialogDrag :visible.sync="storeNumberVisible" @close="storeNumberVisible = false">
      <el-form :model="storeNumberForm" label-position="right" :rules="storeNumberRules" ref="storeNumberForm">
        <el-form-item label="商品加价比例:" prop="storeType" label-width="125px" >
           <el-radio-group v-model="storeNumberForm.storeType">
              <el-radio label="1">控价入驻商家</el-radio>
              <el-radio label="2">服务费入驻商家</el-radio>
            </el-radio-group>
        </el-form-item>
        <el-form-item label="商品加价比例:" prop="rate" label-width="125px" >
          <el-input v-model="storeNumberForm.rate" type="number"  autocomplete="off" placeholder="请输入商品加价比例"><template slot="append">%</template></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="storeNumberVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="editStoreNumberSubmit('storeNumberForm')" size="small" :loading="btnLoading">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 修改加价比例 -->
    <el-dialog title="修改商品加价比例" width="600px" v-dialogDrag :visible.sync="UpMoneyRationVisible" @close="UpMoneyRationVisible = false">
      <el-form id="userDialog" :model="user" label-position="right" :rules="rules" ref="user">
        <el-form-item label="商品加价比例:" prop="ration" label-width="125px" >
          <el-input v-model="user.ration"  autocomplete="off" placeholder="请填写商品加价比例"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="UpMoneyRationVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="editShopUpMoneySubmit('user')" size="small" :loading="btnLoading">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 查看二维码 -->
    <el-dialog :title="dialogTitle" width="800px" v-dialogDrag :visible.sync="qrCodeVisible" @close="qrCodeVisible = false">
      <div class="qrCodeBox d-flex d-flex justify-center">
        <div class="left flex1">
          <p class="title" style="text-align: center;">收款二维码</p>
          <div id="gatheringQrCode" ref="gatheringQrCode">
            <el-image :src="statusRow.shareQrcode" fit="fill"  class="img" v-image-preview></el-image>
          </div>
          <div class="d-flex justify-center" style="margin-top:10px"><el-button size="small" @click="savePic('1')" :loading="btnLoading">下载二维码</el-button></div>
        </div>
        <div class="left flex1">
          <p class="title" style="text-align: center;">分享二维码</p>
          <div id="shareQrCode" ref="shareQrCode">
             <el-image :src="statusRow.custShareQr" fit="fill"  class="img" v-image-preview></el-image>
          </div>
          <div class="d-flex justify-center" style="margin-top:10px"><el-button size="small" @click="savePic('2')" :loading="btnLoading">下载二维码</el-button></div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="qrCodeVisible = false" size="small" :loading="btnLoading">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import common from '@/api/api';
  import QRCode from 'qrcodejs2';
  import qs from 'qs';
  import {
    storeGetList,storeChangeStatus,getStoreInfo,saveStore,updateStore,delStore,updateStoreMcht,BStoreSetRate,
    BgetStoreList,updateStoreStatus
  } from '@/api/getData';
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import option from '../../common/option.js';

  export default {
    components: { Treeselect },
    data() {
      let that = this;
      return {
        sta:true,
        loading: false,
        btnLoading: false,
        imgHost:'',
        storeList:[],
        time:[],
        searchForm: {
          storeName:"",
          pageNum:1,
          pageSize:20,
        },
        levelList:[],
        tableColumn:[],
        hideTableColumn:[],/*自定义表格列需要隐藏的*/
        tableColumnType:'staffManagement',/*自定义表格列类型传参*/
        tableHeight:0,//table 高度
        statusList: [{
          id: '1',
          name: '启用'
        }, {
          id: '2',
          name: '禁用'
        }],
        dataList:[],
        total: 0,
        multipleSelection: '',

        areaProps: {/*地址加载*/
          lazy: true,
          checkStrictly: true,
          lazyLoad (node, resolve) {
            that.$axios({
              method: 'get',
              url: common.apihost+'/system/area/getList?pcode='+(node.value?node.value:'0'),
            }).then ((res) => {
              if (res.data.code == 200) {
                const nodes = res.data.data;
                nodes.forEach(item => {
                  item.value = item.code,
                  item.label = item.name,
                  item.leaf = item.level >= 5
                })
                resolve(nodes);
              } else {
                this.$message.error(res.msg)
              }
            })
          }
        },
        statusRow:{},
        dialogTitle: '',
        UpMoneyRationVisible:false,
        qrCodeVisible:false,
        user: {
          id: '',
          ration: ''
        },
        rules: {
          ration: [{
            required: true,
            name: '请填写商品加价比例',
            trigger: 'blur'
          }]
        },

        storeNumberVisible:false,
        storeNumberForm: {
          storeId: '',
          storeType:'',
          rate:''
        },
        storeNumberRules: {
          storeType: [{
            required: true,
            name: '请选择类型',
            trigger: 'blur'
          }],
          rate: [{
            required: true,
            name: '请输入商家加价比例',
            trigger: 'blur'
          }]
        },
      }
    },
    computed: {
      pickerOptions: () => {
        return option.pickerOptions;
      }
    },
    mounted() {
      this.imgHost = common.imghost;
      this.dataInfo();
     // this.getSelect();
      this.$nextTick(() => {
          this.tableHeight = this.$refs.index.offsetHeight - this.$refs.search.offsetHeight - this.$refs.page.offsetHeight - 55;
      })
    },
    methods: {
      /** 状态修改 **/
      async handleChangeStatus(row) {
        try {
          let data = {
            storeId : row.storeId,
            storeStatus: row.storeStatus
          }
          const result = await updateStoreStatus(data);
          if (result.code == 200) {
            this.$message.success(result.msg);
          } else {
            this.$message.error(result.msg);
            row.status = !row.status;
          }
        } catch (err) {
          console.log(err)
        }
      },
      /** 设置 **/
      handleSet(index,row){
        this.storeNumberForm.storeId = row.storeId;
        this.storeNumberForm.storeType = row.storeType+'';
        this.storeNumberForm.rate = row.markupRate;
        this.storeNumberVisible = true;
      },
      /** 提交修改商品服务费 **/
      editStoreNumberSubmit(formName){
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.btnLoading) return;
            this.btnLoading = true;
            BStoreSetRate(this.storeNumberForm).then((result) => {
              if (result.code == 200) {
                this.$message.success(result.msg);
                this.storeNumberVisible = false;
                this.dataInfo();
              } else {
                this.$message.error(result.msg);
              }
              this.btnLoading = false;
            });
          }
        })
      },
      areaChange(){
         console.log(this.$refs['cascaderAddr'].getCheckedNodes()[0].pathLabels.toString().replaceAll(",",""))
         console.log(this.searchForm.areaCode)
      },
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.categoryId,
          label: node.name,
          children: node.children
        };
      },
      /** 表格排序 **/
      handleTablechangeSort (column, prop, order) {
         this.searchForm.orderByColumn =  column.prop;
        this.searchForm.isAsc = column.order;
        this.dataInfo();
      },
      async dataInfo() {
        try {

          this.loading = true;
          const result = await BgetStoreList(this.searchForm);
          if (result.code == 200) {
            this.total = result.total;
            this.dataList = result.rows;
          } else {
            this.$message.error(result.msg);
          }
          this.loading = false;
        } catch (err) {
          this.loading = false;
          console.log(err)
        }
      },
      getSelect(){
        this.getCategoryDetails({categoryKey:'member_level_category'}).then(res=>{ this.levelList = res.data; })
        this.getCategoryDetails({categoryKey:'stores_category'}).then(res=>{ this.storeList = res.data; })
      },
      handleSearch() {
        this.searchForm.pageNum= 1;
        this.dataInfo();
      },
      handleEdit(index,row){
        this.$router.push({path:'/user/applyStoreNew',query:{storeId:row.storeApplyId,type:'edit',customerId:'',entrance:'user'}});
      },
      handleLook(index,row){
        this.$router.push({path:'/user/applyStoreNew',query:{storeId:row.storeId,type:'detail'}});
      },
      handleRqCode(index,row){
        this.qrCodeVisible = true;
        this.statusRow = row;
        this.dialogTitle = row.name+'的二维码';
      },
      /** 下载二维码 **/
      savePic(type){
          let url = '';
          if(type=='1'){
            url = this.statusRow.shareQrcode;
          }else{
            url = this.statusRow.custShareQr;
          }
          var alink = document.createElement("a");
          alink.href = url;
          alink.download = "pic"; //图片名
          alink.click();
      },
      downloadIamge(imgsrc, name) {//下载图片地址和图片名
        var image = new Image();
        // 解决跨域 Canvas 污染问题
        image.setAttribute("crossOrigin", "anonymous");
        image.onload = function() {
          var canvas = document.createElement("canvas");
          canvas.width = image.width;
          canvas.height = image.height;
          var context = canvas.getContext("2d");
          context.drawImage(image, 0, 0, image.width, image.height);
          var url = canvas.toDataURL("image/png"); //得到图片的base64编码数据

          var a = document.createElement("a"); // 生成一个a元素
          var event = new MouseEvent("click"); // 创建一个单击事件
          a.download = name || "photo"; // 设置图片名称
          a.href = url; // 将生成的URL设置为a.href属性
          a.dispatchEvent(event); // 触发a的单击事件
        };
        image.src = imgsrc;
      },
      resetQuery() {
        this.time = [];
        this.resetForm("searchForm");
        this.dataInfo();
      },
      handleEditUpMoneyRation(index,row){
        this.UpMoneyRationVisible = true;
      },
      handleDelt(index,row){
          this.$confirm('您确定要删除吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            delStore({storeId:row.storeId}).then((result) => {
                  if (result.code == '200') {
                       this.dataInfo();
                       this.$message({
                           message: result.msg,
                           type: 'success'
                         });
                   }else{
                      this.$message.error(result.msg);
                   }
               });
          }).catch(() => {
          });
      },
      /** 修改商品加价比例提交 **/
      editShopUpMoneySubmit(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.btnLoading) return;
            this.btnLoading = true;
            getCallRecord(this.user).then((result) => {
              if (result.success == true) {
                this.$message.success(result.message);
                this.userFormVisible = false;
                this.dataInfo();
              } else {
                this.$message.error(result.message);
              }
              this.btnLoading = false;
            });
          }
        })
      },
      handleAdd(){
         this.$router.push({path:'/user/addUser'});
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
    }
  }
</script>

<style scoped lang="scss">
  .searchAddress /deep/ .el-input{
    width:380px!important;
  }
  #gatheringQrCode,#shareQrCode{
    display:flex;
    justify-content:center;
  }
  .el-table .el-dropdown-link{
      cursor: pointer;
      color: #61997A;
      margin-left: 5px;
  }
    .leftDialog{
      height:540px;
      overflow-y: auto;
    }
    .activeVerticalBox .activeItem{
      color:#61997A;
      cursor: pointer;
      margin: 0px;
      text-align: center;
      height:20px;
      line-height: 20px;
    }
    .activeVerticalBox .el-dropdown{
      display: flex;
      justify-content: center;
      color:#61997A;
      cursor: pointer;
    }
    .activeCheckedBox{
      border-top: 1px solid #ddd;
      padding:10px;
      height:52px;
      .el-tag{
        margin-right:10px;
      }
    }
    .rateBox /deep/ .el-rate__icon{
      margin-right: 0px;
    }
    .rateBox>p{
      margin: 0px;
    }
    .rateBox>p> /deep/ .el-rate{
      height:25px;
      line-height:25px;
      display:flex;
    }
    .rateBox>p> /deep/ .el-rate .el-rate__item{
      display:flex;
      align-items: center;
    }
    .rateBox .rateText{
      width:60px;
    }
    .rateBox .content{
      display: flex;
    }
    .rateBox .el-tooltip{
          width: 100px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          display: inline-block;
    }
</style>
